package com.woniuxy.auth.controller;

import com.woniuxy.commons.entity.User;
import com.woniuxy.commons.enums.ResultEnum;
import com.woniuxy.commons.util.JwtUtil;
import com.woniuxy.commons.util.ResponseResult;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * @Author zhangyong
 * @Date 2021/8/5 0005下午 2:30
 */
@RestController
@RequestMapping("/auth")
public class AuthController {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @PostMapping("/login")
    public ResponseResult login(@RequestBody User user, HttpServletResponse response){
        //1、通过账号作为查询条件，查询数据库
        //2、如果对比成功，说明登录成功
        //3、利用工具类生成token  返回前端
        String token = JwtUtil.generateToken(user.getAccount());
        //刷新token
        String refreshToken = UUID.randomUUID().toString();
        //将token、refreshToken放入redis
        /*
            refreshToken作为key，token和account作为value
            refreshToken:{    过期时间30天
                token: xxxx,  1小时过期
                account: xxxx
            }
         */

        Map<String, Object> map = new HashMap<>();
        map.put("token",token);
        map.put("account",user.getAccount());
        //
        redisTemplate.opsForValue().set(refreshToken,map);
        // 设置过期时间
        redisTemplate.expire(refreshToken,30, TimeUnit.DAYS);


        //通过响应头返回给前端
        response.setHeader("authorization",token);
        response.setHeader("refreshToken",refreshToken);
        //暴露头   暴露多个头用逗号隔开
        response.setHeader("Access-Control-Expose-Headers","authorization,refreshToken");
        //response.setHeader("Access-Control-Expose-Headers","refreshToken");


        return null;
    }


    /**
     * 接收account、perms，通过account查询数据得到当前用户的全部权限信息
     * 然后与传进来的perms进行对比，返回结果
     */
    @GetMapping("/perms/{account}/{perms}")
    public ResponseResult existPerms(@PathVariable("account") String account , @PathVariable("perms") String perms){
        //通过account查询数据得到当前用户的全部权限信息
        //假设得到了当前用户所有的权限信息
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(200);
        responseResult.setStatus(ResultEnum.PERMS_NO);//默认为no
        responseResult.setMessage("你没有权限");

        List<String> permsList = Arrays.asList("goods:all","goods:del","goods:update");
        //包含
        if(permsList.contains(perms)){
            responseResult.setMessage("当前用户"+account+"拥有"+perms+"权限");
            responseResult.setStatus(ResultEnum.PERMS_YES);
        }
        //
        return responseResult;
    }
}



